import esbuild from 'esbuild'
import fs from 'node:fs'
import {createRequire} from 'node:module'
import {fileURLToPath} from "node:url"
import {dirname, resolve} from 'node:path'
import {parseArgs} from 'node:util'
import {polyfillNode} from 'esbuild-plugin-polyfill-node'

/*
* 这里我们是使用 esbuild 在开发环境来进行打包，
* 在真正的生产环境中，我们会使用 rollup 来进行打包，
* 因为 rollup 的 tree-shaking 做得更好
* */


// 可以在 ES 模块中使用 CommonJS 的 require
const require = createRequire(import.meta.url)
// 获取当前模块的目录名 dirname 是目录名
// fileURLToPath: 将 URL 转换为文件路径
// import.meta.url 是文件 file 的 URL 格式
const __dirname = dirname(fileURLToPath(import.meta.url)) // 文件目录

// 初始化参数
const {
    values: {format: rawFormat, prod, inline: inlineDeps},
    positionals,
} = parseArgs({
    allowPositionals: true,
    options: {
        format: {
            type: 'string',
            short: 'f',
            default: 'global',
        },
        prod: {
            type: 'boolean',
            short: 'p',
            default: false,
        },
        inline: {
            type: 'boolean',
            short: 'i',
            default: false,
        },
    },
})

const format = rawFormat || 'global'
const targets = positionals.length ? positionals : ['vue']

// 输出格式
const outputFormat = format.startsWith('global')
    ? 'iife'
    : format === 'cjs'
        ? 'cjs'
        : 'esm'

const postfix = format.endsWith('-runtime')
    ? `runtime.${format.replace(/-runtime$/, '')}`
    : format

const privatePackages = fs.readdirSync('packages-private')


console.log('dirname', rawFormat)
console.log('dirname', prod)
console.log('require', inlineDeps)
console.log('require', positionals)
console.log('targets', targets)
console.log('outputFormat', outputFormat)
console.log('postfix', postfix)
console.log('privatePackages', privatePackages)


for (const target of targets) {
    // 判断是否是私有包
    const packBase = privatePackages.includes(target)
        ? `packages-private`
        : `packages`

    // 获取对应包的相对路径
    const packBasePath = `../${packBase}/${target}`
    // 获取包的 package.json 文件
    const pkg = require(`${packBasePath}/package.json`)
    // 输出的文件地址
    const outfile = resolve(
        __dirname,
        `${packBasePath}/dist/${
            target === 'vue-compat' ? `vue` : target
        }.${postfix}.${prod ? `prod.` : ``}js`,
    )

    console.log('outfile', outfile)
    console.log('outfile', packBase)
    console.log('outfile', process.cwd())
    console.log('outfile', __dirname)
    const relativeOutfile = resolve(process.cwd(), outfile)
    console.log('outfile', relativeOutfile)
    console.log(!inlineDeps)

    let external = []
    if (!inlineDeps) {
        console.log("format", format)
        console.log("target", target)
    }
    const plugins = [
        {
            name: 'log-rebuild',
            setup(build) {
                build.onEnd(() => {
                    console.log(`built: ${relativeOutfile}`)
                })
            },
        },
    ]

    if (format !== 'cjs' && pkg.buildOptions?.enableNonBrowserBranches) {
        plugins.push(polyfillNode())
    }

    esbuild
        .context({
            entryPoints: [resolve(__dirname, `${packBasePath}/src/index.ts`)],
            // 输出文件
            outfile,
            bundle: true,
            external,
            sourcemap: true,
            format: outputFormat,
            globalName: pkg.buildOptions?.name,
            platform: format === 'cjs' ? 'node' : 'browser',
            plugins,
            define: {
                __COMMIT__: `"dev"`,
                __VERSION__: `"${pkg.version}"`,
                __DEV__: prod ? `false` : `true`,
                __TEST__: `false`,
                __BROWSER__: String(
                    format !== 'cjs' && !pkg.buildOptions?.enableNonBrowserBranches,
                ),
                __GLOBAL__: String(format === 'global'),
                __ESM_BUNDLER__: String(format.includes('esm-bundler')),
                __ESM_BROWSER__: String(format.includes('esm-browser')),
                __CJS__: String(format === 'cjs'),
                __SSR__: String(format !== 'global'),
                __COMPAT__: String(target === 'vue-compat'),
                __FEATURE_SUSPENSE__: `true`,
                __FEATURE_OPTIONS_API__: `true`,
                __FEATURE_PROD_DEVTOOLS__: `false`,
                __FEATURE_PROD_HYDRATION_MISMATCH_DETAILS__: `true`,
            },
        })
        .then(ctx => ctx.watch())
}


run()

function run() {


}
